import json

from django.db import transaction
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View

from rest_framework.generics import ListAPIView, RetrieveAPIView, CreateAPIView
from rest_framework.permissions import IsAuthenticated

from Headlines.models import Channel, Article, Comment
from articles.serializers import ChannelModelSerializer, ArticleModelSerializer, ArticleModelSerializer1, \
    ArticleSearchModelSerializer, ArticlesimpleSerializer
from articles.utils import PageNum
from users.models import User


class ChannelView(ListAPIView):
    # 获取所有频道
    queryset = Channel.objects.all()
    serializer_class = ChannelModelSerializer
    pagination_class = PageNum


class ArticlelView(ListAPIView):
    # 获取频道下文章列表
    serializer_class = ArticleModelSerializer
    pagination_class = PageNum
    lookup_field = 'id'
    def get_queryset(self):
        id = self.kwargs['id']
        if id=='-1':
            return Article.objects.all().order_by('-comment_count')
        else:
            return Article.objects.filter(channel_id=id)




class ArticledetailView(RetrieveAPIView):
    # 获取文章详情
    queryset = Article.objects.all()
    serializer_class = ArticleModelSerializer1
    lookup_field = 'id'


class ClollectarticleView(RetrieveAPIView):

    # 收藏或者取消收藏功能
    queryset = Article.objects.all()
    serializer_class = ArticlesimpleSerializer
    permission_classes = [IsAuthenticated]
    # 收藏或者取消收藏功能
    def put(self, request, id):
        article = Article.objects.get(id=id)
        article_users = article.collected_users.all()
        if request.user in article_users:
            article.collected_users.remove(request.user)
            article.save()
            return JsonResponse({'success': 'true', 'message': '取消收藏'})
        else:
            article.collected_users.add(request.user)
            article.save()
            return JsonResponse({'success': 'true', 'message': '收藏成功'})


class AddArticleView(CreateAPIView):
    # 发布文章
    queryset = Article.objects.all()
    serializer_class = ArticlesimpleSerializer
    def post(self, request, *args, **kwargs):
        data = json.loads(request.body.decode())
        labels = data.get('labels')
        image=data.get('image')
        try:
            article=Article.objects.create(user=request.user,title=data['title'],content=data['content'],channel_id=data['channel'],image=image)
        except Exception as e:
            return None
        for label in labels:
            article.labels.add(label)
        return JsonResponse({"articleid": article.id,
                             "message": "发布成功",
                             "success": "true"})

class ArticlecommentView(CreateAPIView):
    # 新增评论
    queryset = Article.objects.all()
    serializer_class = ArticlesimpleSerializer
    def post(self, request, id):
        try:
            user = request.user
        except Exception as e:
            user = None
        if user is not None or user.is_is_authenticated:
            data = json.loads(request.body.decode())
            content = data.get('content')
            parent = data.get('parent')
            try:
                article = Article.objects.get(id=id)
            except Exception as e:
                return None
            if parent:
                try:
                    comment=Comment.objects.get(article=article,id=int(parent))
                except Exception as e:
                    return None
                if article.comment_count:
                    article.comment_count += 1
                else:
                    article.comment_count = 0
                article.save()
                Comment.objects.create(user=request.user, content=content, article=article, parent=comment)
                return JsonResponse({"message": "新增评论成功", "success": "true"})
            else:
                try:
                    Comment.objects.create(user=request.user,content=content, article=article)
                except Exception as e:
                    return None
                if article.comment_count:
                    article.comment_count =article.comment_count
                else:
                    article.comment_count=0
                article.comment_count+=1
                article.save()
                return JsonResponse({"message": "新增评论成功", "success": "true"})
        return JsonResponse({"errmsg":"error"})



class ArticleSearchView(ListAPIView):
    # 文章搜索功能
    serializer_class = ArticleSearchModelSerializer
    pagination_class =PageNum
    lookup_field ='content'
    def get_queryset(self):
        text=self.request.query_params.get('text')
        if text:
            return Article.objects.filter(content__contains=text)

        else:
            return Article.objects.all()
